/**
 * Created by budao on 2020/09/04.
 */
import React from 'react';
import {Modal, Button,Row,Col,Cascader,Input,Form,message} from 'antd';
import styles  from './Bmap.less';
import { request } from 'config/request'
const { Component } = React
import { cloneDeep,isEqual } from 'lodash';
// 引入全局配置
import config from '../../config/config'
// 异步静态资源


let count = 0, libs = [
  'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
  'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
  'https://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js'
];
const head = document.getElementsByTagName('head')[0];
/*
 *
 * 地图组件
 *
 */

export default class Bmap extends Component {
    constructor(props) {
      super(props);
      this.state = {
        center:'',
        map:null,//地图实例
        markers:[],
        province:null
      }
      this.setMapRef = ref => {
        this.mapContainer = ref;
      };
    }
  
    async componentDidMount() {
        if(!this.map){
          this.createMapScript().then(this.initMap);
        }
    }
  
    componentWillReceiveProps(nextProps) {
      if(this.map){
        // console.log(nextProps.provinceData)
        this.addOverlayGroup(nextProps)
        if(nextProps.provinceData){
        //   this.add_overlay(nextProps)
        }
        if(nextProps.province){
          this.setState({
            province:nextProps.province
          })
        }
      }else{
        //tabs切换 组件已销毁，但是地图资源已加载，不需要再次加载地图资源
        this.initMap()
      }
    }

    addOverlayGroup(payload){

      var _this = this

      let {map,maps,markerClusterer} = _this
      let {markers,province,center} = _this.state
      // if(){

      // }
      // let centers = center?{lng:center.lng,lat:center.lat}:{lng:116.331398,lat:39.897445}
      let beijinPoint = new BMap.Point(116.331398,39.897445);
      let centers =center? new BMap.Point(center.lng,center.lat):''
      var point = centers|| province || beijinPoint
      let zoom = payload.provinceData.length?5:5
      map.centerAndZoom(point,zoom)
      if(markerClusterer){
        markerClusterer.clearMarkers(markers)
        markers = this.markerssFun(payload.markers)
        //添加聚合点
        markerClusterer.addMarkers(markers)
      }else{
        markers = this.markerssFun(payload.markers)
        // 第一次新增挂到全局
        //MarkerClusterer 首次 必须要先设置中心坐标点，否则报错，而且设置的坐标点必须是经纬度，不能够用名称去设置
        markerClusterer = new maps.MarkerClusterer(map, {markers:markers});
        _this.markerClusterer = markerClusterer
      }
      
      _this.setState({markers})
    }
    add_overlay(payload){
      let {map} = this
      var _this = this
      let len = payload.provinceData.length
      var i = 0;
      if(len){
      // 函数 创建多个文本标注
      function markerFun (points,index) {
        // var marker = new BMap.Marker(points);
        var opts = {
          position : points    // 指定文本标注所在的地理位置
        }
        var label = new BMap.Label(payload.provinceData[index].count, opts);  // 创建文本标注对象
        label.setStyle({
          padding:"6px",
          fontSize : "12px",
          fontFamily:"微软雅黑",
          border:"none",
          background:"rgba(255,100,97,0.5)",
          color:"#fff",
          borderRadius:"50%",
        });
        label.addEventListener("click",_this.clickProvince.bind(_this));
        map.addOverlay(label);
      }
      for (;i<len;i++) {
        var points = new BMap.Point(payload.provinceData[i].lng,payload.provinceData[i].lat);//创建坐标点
        markerFun(points,i);
      }
      
      }
    }
    clickProvince(e){
      let {map} = this
      e=e || window.event;
      let {point} = e.target
      console.log(e)
      map.centerAndZoom(point,8);
      // let center = e.target.getCenter()
      // 根据坐标查询地址
      this.geoc.getLocation(point,(rs)=>{
        // console.log(rs)
        let province = rs.addressComponents.province
        let point = rs.point
        // console.log(province)
        this.props.getProvince(province)
      })
      // this.props.getProvince(this.state.province)
    }
    
    //点聚合数据处理
    markerssFun(m){
        let markers = []
        var MAX = m.length;
        var pt = null;
        var i = 0;
        for (; i < MAX; i++) {
            if(m[i].lng){
                pt = new BMap.Point(m[i].lng, m[i].lat);
                markers.push(new BMap.Marker(pt));
            }
        }
        return markers
    }

  
    shouldComponentUpdate() {
      return !this.inited;
    }
  
    componentWillUnmount() {
      if (this.map) {
        this.map = null;
      }
      if (this.map) {
        this.maps = null
      }
      if(this.markerClusterer){
        this.markerClusterer = null
      }
    }
  
  
    initMap=()=>{
      let {markers,center} = this.state
      let {BMap,BMapLib={}} = window
      
      
      // 百度地图API功能
      var map = new BMap.Map(this.mapContainer);
      var maps = BMapLib
      var point = new BMap.Point(116.331398,39.897445);
       //定位拾坐标
      var geoc = new BMap.Geocoder();

      map.centerAndZoom(point,5);
      map.enableScrollWheelZoom();// 开启/禁用 滚动缩放
      map.disableDoubleClickZoom();//禁用鼠标双击放大
    //   map.addEventListener('onzoomend',this.onzoomendFun.bind(this));

      this.map = map;
      this.maps = maps;
      this.geoc = geoc;

    };
    onzoomendFun(e){
      // console.log(this)
      e=e || window.event;
      // console.log(e.target.getZoom())
      // let center = e.target.getCenter()
      // //根据坐标查询地址
      // this.geoc.getLocation(center,(rs)=>{
      //   // console.log(rs)
      //   let province = rs.addressComponents.province
      //   let point = rs.point
      //   console.log(province)
      //   this.setState({
      //     province,
      //     center:point
      //   })
      //   this.props.getProvince(province)
      // })
    }
    createMapScript = () =>{
      var self = this
      const ak = 'Q17CQo5pl4GPDqxmsgXwqLGYxTCijbrh';
      return new Promise((resolve, reject) => {
        if (window.BMap && Window.BMapLib) {
            // 已经加载则直接返回
            console.log('map already exist');
            resolve({BMap: window.BMap, BMapLib: window.BMapLib});
        } else {
            // 异步加载
            console.log('async load map');
            const bmap = document.createElement('script');
            bmap.type = 'text/javascript';
            bmap.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=MapLoadSuccess`;

            const bmapMeta = document.createElement('meta');
            bmapMeta['http-equiv'] = "Content-Security-Policy";
            bmapMeta['content']="upgrade-insecure-requests";

            head.appendChild(bmap);
            window.MapLoadSuccess = function() {
                // BMap加载完成，开始加载libs
                libs.forEach(lib => {
                  self.loadLib(lib, resolve, reject);
                })
            }
            bmap.onerror = function() {
                reject('地图初始化失败');
            }
        }
    })
    }

    loadLib(src, resolve, reject) {
      const lib = document.createElement('script');
      lib.setAttribute('type', 'text/javascript');
      lib.setAttribute('src', src);
      lib.onerror = function() {
          reject('地图初始化失败');
      }
      lib.onload = function() {
          count += 1;
          if (count === libs.length) { // libs全部加载成功才返回
              resolve({BMap: window.BMap, BMapLib: window.BMapLib});
          }
      }
      head.appendChild(lib);
  }
    
    render() {
      const { width = '100%', height = 700, style } = this.props;
  
      return (
        <div style={{ border: 'solid 1px #e1e1e1', marginBottom: 16, borderRadius: 5 }}>
          <div ref={this.setMapRef} style={{ width, height, ...style }} />
        </div>
      );
    }
  }